﻿using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace MQTT.Model.Servers
{
    public class UserEntityService
    {
        private readonly IMongoCollection<UserEntity> _users;

        public UserEntityService()
        {
            DatabaseSettings settings = new();
            var client = new MongoClient(settings.ConnectionString);
            var database = client.GetDatabase(settings.DatabaseName);

            _users = database.GetCollection<UserEntity>(settings.MQTTChatCollectionName);
        }

        public List<UserEntity> Get()=>
            _users.Find(user => true).ToList();

        public UserEntity Get(string id) =>
            _users.Find(user => user.Id == id).FirstOrDefault();

        public async Task<UserEntity> Get(Expression<Func<UserEntity, bool>> filter) =>
           await _users.Find(filter).FirstOrDefaultAsync();

        public async Task<bool> ExistAsync(Expression<Func<UserEntity, bool>> filter) =>
            await _users.Find(filter).AnyAsync();

        public async Task<UserEntity> CreateAsync(UserEntity user)
        {
            await _users.InsertOneAsync(user);
            return user;
        }

        public async Task Update(string id, UserEntity userIn) =>
           await _users.ReplaceOneAsync(user => user.Id == id, userIn);

        public async Task Remove(UserEntity userIn) =>
          await _users.DeleteOneAsync(user => user.Id == userIn.Id);

        public async Task Remove(string id) =>
           await _users.DeleteOneAsync(user => user.Id == id);
    }
}
